package hiatao.puzzle.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.util.ArrayList;
import java.util.List;

import haitao.imagefilter.BlackWhiteFilter;
import haitao.imagefilter.FillPatternFilter;
import haitao.imagefilter.IImageFilter;
import haitao.imagefilter.IllusionFilter;
import haitao.imagefilter.Image;
import haitao.imagefilter.RainBowFilter;
import haitao.imagefilter.RectMatrixFilter;
import haitao.imagefilter.SharpFilter;
import haitao.imagefilter.ShiftFilter;
import haitao.imagefilter.ThreeDGridFilter;
import haitao.imagefilter.TileReflectionFilter;
import haitao.imagefilter.VideoFilter;
import haitao.imagefilter.ZoomBlurFilter;
import haitao.imagefilter.textures.LabyrinthTexture;
import haitao.imagefilter.textures.TextileTexture;
import haitao.imagefilter.textures.TexturerFilter;
import haitao.puzzle.R;
import hiatao.puzzle.inter.SaveImageCallback;
import hiatao.puzzle.utils.BitmapSaveUtils;
import hiatao.puzzle.utils.FileUtils;
import hiatao.puzzle.utils.ImageUtils;
import hiatao.puzzle.utils.PixelUtil;
import hiatao.puzzle.utils.StatusBarCompat;
import hiatao.puzzle.utils.Tools;

public class PhotoProcessActivity  extends Activity implements OnClickListener{

	private ImageView img;
    private View line1;
    private View line2;
    private View rank_tv;
    private View comment_tv;
    private View top_back;
    private View hv;
    private LinearLayout layout;
    private LinearLayout act;
    private LinearLayout pattern;
    private String path;
    private String path2;
    private boolean hasChage;
    private Bitmap tempBitmap;
    List<IImageFilter> filterArray = new ArrayList<IImageFilter>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_picture_process);
		findView();
		init();
		StatusBarCompat.compat(this, getResources().getColor(R.color.primary));
	}

	private void init() {
		LayoutParams lp = (LayoutParams) img.getLayoutParams();
		int s= PixelUtil.getScreenWidth(this);
		lp.height=s-PixelUtil.dp2px(this, 20);
		lp.width = s-PixelUtil.dp2px(this, 20);
		img.setLayoutParams(lp);
		path2=getIntent().getStringExtra("URL");
		path= path2.replace("file:///", "");
		comment_tv.setOnClickListener(this);
		rank_tv.setOnClickListener(this);
		top_back.setOnClickListener(this);
		// 计算下面的高度
		int height = PixelUtil.getScreenHeightNoBar(this)-(int)Tools.getDimension(R.dimen.title_height)-PixelUtil.getScreenWidth(this)-PixelUtil.dp2px(this, 50)-PixelUtil.dp2px(this, 50)-PixelUtil.dp2px(this, 16)+PixelUtil.dp2px(this, 10);
		
		filterArray.add(null);// 原图
		filterArray.add(new VideoFilter(VideoFilter.VIDEO_TYPE.VIDEO_TRIPED));//2
		filterArray.add(new TexturerFilter(new TextileTexture(), 0.8f, 0.8f));//17
		//filterArray.add( new SharpFilter());//48
		filterArray.add(new BlackWhiteFilter());//62
		filterArray.add(new RainBowFilter());//96
		filterArray.add( new ThreeDGridFilter(16, 100));//28
		filterArray.add(new ShiftFilter(10));//38
		filterArray.add(new FillPatternFilter(this, R.drawable.texture2));//8
		filterArray.add(new TexturerFilter(new LabyrinthTexture(), 0.8f, 0.8f));//14
		filterArray.add( new SharpFilter());//48
		filterArray.add(new RectMatrixFilter());//75
		filterArray.add(new ZoomBlurFilter(30));//27
		filterArray.add(new TileReflectionFilter(20, 8));//34
		filterArray.add(new IllusionFilter(3));//43
		
		layout = (LinearLayout) findViewById(R.id.id_gallery);
		pattern = (LinearLayout) findViewById(R.id.pattern);
		act = (LinearLayout) findViewById(R.id.act);
		// 先设置 图片的高度
		for(int i=0;i<filterArray.size();i++){
			final ImageView iv = (ImageView) layout.getChildAt(i);
			iv.setTag(i+"");
			LayoutParams lp2 = (LayoutParams) iv.getLayoutParams();
			lp2.height=height;
			lp2.width = height;
			iv.setLayoutParams(lp2);
			final int position =i;
			iv.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					changge(position);
				}
			});
		}
		// 为了加快速度
		//生成小图 small_pic
		ImageUtils.loadImg(path2,img);
		ImageLoader.getInstance().loadImage(path2, new SimpleImageLoadingListener()
        {
				public void onLoadingComplete(String imageUri, android.view.View view, final android.graphics.Bitmap loadedImage) {
            	runOnUiThread(new Runnable() {
					@Override
					public void run() {
						FileUtils.saveFileNewThread(PhotoProcessActivity.this, loadedImage, 100, new SaveImageCallback() {
							@Override
							public void saveResult(boolean reslut, final String allPath) {
								path=allPath;
								for(int i=0;i<filterArray.size();i++){
									final ImageView iv = (ImageView) layout.getChildAt(i);
									//iv.setTag(i+"");
									final int s = i;
									runOnUiThread(new Runnable() {
										public void run() {
											//ImageUtils.loadImg(allPath, iv);
											if(filterArray.get(s)!=null){
												new processImageTask(PhotoProcessActivity.this, filterArray.get(s),iv).execute();
												//ImageUtils.loadImg(path, iv);
											}else{
												ImageUtils.loadImg("file:///"+path, iv);
											}
										}
									});
									
								}
							}
						});
					}
				});
            	};
        	}
        );
		
		
		
	
		findViewById(R.id.confirm).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(hasChage){
					Tools.showWaitDialog(PhotoProcessActivity.this, "图片保存中", false);
					String filename = FileUtils.createFileNmae(".jpg");
					BitmapSaveUtils.saveBmpToSd(FileUtils.getAppPath(),tempBitmap,filename,100,true);
					Tools.dismissWaitDialog();
					Intent intent = new Intent();
					intent.setClass(PhotoProcessActivity.this, PreViewActivity.class);
					intent.putExtra("URL","file:///"+FileUtils.getAppPath()+filename);
					startActivity(intent);
					finish();
				}else{
					Intent intent = new Intent();
					intent.setClass(PhotoProcessActivity.this, PreViewActivity.class);
					intent.putExtra("URL",path2);
					startActivity(intent);
					finish();
				}
			}
		});
		
	}
	void changge(int position){
		if(position==0){
			hasChage =false;
			ImageUtils.loadImg(path2,img);
			tempBitmap =null;
		}else{
			Tools.showWaitDialog(this, "图片生成中", false);
			new MyThread(filterArray.get(position),img).start();
		}
	}
	public class MyThread extends Thread{
		private IImageFilter filter;
        private ImageView iv;
		public MyThread(IImageFilter imageFilter,ImageView iv) {
			this.filter = imageFilter;
			this.iv=iv;
		}

		@Override
		public void run() {
			super.run();
			Image img = null;
			try
	    	{
				//final Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/1.jpg");
				final Bitmap bitmap = BitmapFactory.decodeFile(path);
				img = new Image(bitmap);
				if (filter != null) {
					img = filter.process(img);
					img.copyPixelsFromBuffer();
					final Bitmap b = img.getImage();
					tempBitmap= b;
					runOnUiThread(new  Runnable() {
						public void run() {
							Tools.log("ok");
							iv.setImageBitmap(b);	
							hasChage = true;
							Tools.dismissWaitDialog();
						}
					});
				}
	    	}
			catch(Exception e){
				System.out.println(e);
				if (img != null && img.destImage.isRecycled()) {
					img.destImage.recycle();
					img.destImage = null;
					System.gc(); // 提醒系统及时回收
				}
			}
			finally{
				Tools.dismissWaitDialog();
				if (img != null && img.image.isRecycled()) {
					img.image.recycle();
					img.image = null;
					System.gc(); // 提醒系统及时回收
				}
			}
			
		}
	}
	public class processImageTask extends AsyncTask<Void, Void, Bitmap> {
		private IImageFilter filter;
        private ImageView iv;
		public processImageTask(Activity activity, IImageFilter imageFilter,ImageView iv) {
			this.filter = imageFilter;
			this.iv=iv;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		public Bitmap doInBackground(Void... params) {
			Image img = null;
			try
	    	{
				Bitmap bitmap = BitmapFactory.decodeFile(path);
				img = new Image(bitmap);
				// 这边是处理的
				if (filter != null) {
					img = filter.process(img);
					img.copyPixelsFromBuffer();
					
				}
				//BitmaptoCard.saveBmpToSd(FileUtils.getAppPath(),img.getImage(),"effect"+iv.getTag()+".jpg",20,false);
				return img.getImage();
	    	}
			catch(Exception e){
				if (img != null && img.destImage.isRecycled()) {
					img.destImage.recycle();
					img.destImage = null;
					System.gc(); 
				}
			}
			finally{
				if (img != null && img.image.isRecycled()) {
					img.image.recycle();
					img.image = null;
					System.gc(); 
				}
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Bitmap result) {
			if(result != null){
				super.onPostExecute(result);
				iv.setImageBitmap(result);	
			}
		}
	}
	private void findView() {
        img = (ImageView) findViewById(R.id.img);
        line1 = findViewById(R.id.line1);
        line2 = findViewById(R.id.line2);
        rank_tv = findViewById(R.id.rank_tv);
        comment_tv= findViewById(R.id.comment_tv);
        top_back =  findViewById(R.id.top_back);
        hv =  findViewById(R.id.hv);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rank_tv:
			changeCom(1);
			break;
		case R.id.comment_tv:
			changeCom(2);
			break;
		case R.id.top_back:
			finish();
			break;

		default:
			break;
		}
	}
	private void changeCom(int index){
		if(index==1){
			line1.setBackgroundColor(getResources().getColor(R.color.head_color));
			line2.setBackgroundColor(0);
			pattern.setVisibility(View.GONE);
			pattern.setVisibility(View.GONE);
			hv.setVisibility(View.VISIBLE);
		}else{
			line2.setBackgroundColor(getResources().getColor(R.color.head_color));
			line1.setBackgroundColor(0);
			pattern.setVisibility(View.VISIBLE);
			act.setVisibility(View.VISIBLE);
			hv.setVisibility(View.GONE);
		}
	}
}
